package com.approval.controller;

import com.approval.dto.*;
import com.approval.security.RequirePermission;
import com.approval.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/users")
@CrossOrigin(origins = "*")
@RequirePermission(resource = "user", action = "list")
public class UserManagementController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 创建用户
     */
    @PostMapping
    public ResponseEntity<Result<UserResponse>> createUser(@Valid @RequestBody UserCreateRequest request) {
        try {
            UserResponse user = userService.createUser(request);
            return ResponseEntity.ok(Result.success(user));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 更新用户
     */
    @PutMapping("/{id}")
    public ResponseEntity<Result<UserResponse>> updateUser(@PathVariable Long id, @Valid @RequestBody UserUpdateRequest request) {
        try {
            UserResponse user = userService.updateUser(id, request);
            return ResponseEntity.ok(Result.success(user));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Result<Void>> deleteUser(@PathVariable Long id) {
        try {
            userService.deleteUser(id);
            return ResponseEntity.ok(Result.success());
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 根据ID获取用户
     */
    @GetMapping("/{id}")
    public ResponseEntity<Result<UserResponse>> getUserById(@PathVariable Long id) {
        try {
            UserResponse user = userService.getUserById(id);
            return ResponseEntity.ok(Result.success(user));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 分页查询用户
     */
    @GetMapping
    public ResponseEntity<Result<PageResponse<UserResponse>>> getUsers(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String department,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "id") String sortField,
            @RequestParam(defaultValue = "asc") String sortOrder) {
        try {
            PageRequestDto pageRequest = new PageRequestDto();
            pageRequest.setPage(page);
            pageRequest.setSize(size);
            pageRequest.setSortField(sortField);
            pageRequest.setSortOrder(sortOrder);
            
            PageResponse<UserResponse> users = userService.getUsers(pageRequest, keyword, department, status);
            return ResponseEntity.ok(Result.success(users));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 启用/禁用用户
     */
    @PutMapping("/{id}/status")
    public ResponseEntity<Result<Void>> updateUserStatus(@PathVariable Long id, @RequestParam Integer status) {
        try {
            userService.updateUserStatus(id, status);
            return ResponseEntity.ok(Result.success());
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 重置用户密码
     */
    @PutMapping("/{id}/password/reset")
    public ResponseEntity<Result<Void>> resetUserPassword(@PathVariable Long id, @Valid @RequestBody PasswordResetRequest request) {
        try {
            request.setUserId(id);
            userService.resetUserPassword(request);
            return ResponseEntity.ok(Result.success());
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 修改密码
     */
    @PutMapping("/{id}/password/change")
    public ResponseEntity<Result<Void>> changePassword(@PathVariable Long id, @Valid @RequestBody PasswordChangeRequest request) {
        try {
            userService.changePassword(id, request);
            return ResponseEntity.ok(Result.success());
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 批量操作用户
     */
    @PostMapping("/batch")
    public ResponseEntity<Result<Void>> batchOperation(@Valid @RequestBody BatchUserOperationRequest request) {
        try {
            userService.batchOperation(request);
            return ResponseEntity.ok(Result.success());
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 获取用户权限预览
     */
    @GetMapping("/{id}/permissions")
    public ResponseEntity<Result<UserPermissionPreviewResponse>> getUserPermissionPreview(@PathVariable Long id) {
        try {
            UserPermissionPreviewResponse preview = userService.getUserPermissionPreview(id);
            return ResponseEntity.ok(Result.success(preview));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
    
    /**
     * 导出用户数据
     */
    @GetMapping("/export")
    public ResponseEntity<Result<List<UserResponse>>> exportUsers() {
        try {
            List<UserResponse> users = userService.getAllUsers().stream()
                .map(user -> {
                    UserResponse response = new UserResponse();
                    response.setId(user.getId());
                    response.setUsername(user.getUsername());
                    response.setName(user.getName());
                    response.setEmail(user.getEmail());
                    response.setPhone(user.getPhone());
                    response.setStatus(user.getStatus());
                    response.setCreateTime(user.getCreateTime());
                    return response;
                })
                .collect(java.util.stream.Collectors.toList());
            return ResponseEntity.ok(Result.success(users));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
}